package com.sven.rxandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/*
*  这里创建了Observable，用来发送一字符串，然后创建了Subscriber，用来接收事件处理，然后把这两个绑定，按下按钮后，
*  subscriber会调用onNext方法和onCompleted方法。
* */

public class SimpleActivity extends AppCompatActivity {

    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.btn)
    Button btn;

    private static final String TAG = "SimpleActivity";
    private Subscriber<String> subscriber;/*订阅者*/
    private Observable<String> observable;/*被观察者*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple);
        ButterKnife.bind(this);
        createObservable();
        createSubscriber();
    }

    /*观察者与订阅者绑定*/
    private void bindSubscriber() {
        observable.subscribe(subscriber);
    }

    /*创建订阅者*/
    private void createSubscriber() {

        subscriber = new Subscriber<String>() {

            @Override
            public void onCompleted() {
                Log.e(TAG, "onCompleted");
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(String t) {
                Log.e(TAG, "onNext");
                tv.setText(t);
            }
        };
    }

    /*获取字符串*/
    private String getHello() {
        return "Hello RxAndroid";
    }

    /*创建被观察者*/
    private void createObservable() {
        Log.e(TAG, "observable");
        observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext(getHello());
                subscriber.onCompleted();
            }
        });
    }

    @OnClick({R.id.tv, R.id.btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv:
                break;
            case R.id.btn:
                bindSubscriber();
                break;
        }
    }
}
